import * as echarts from "echarts";
// import "echarts-liquidfill";
import { onMounted, onBeforeUnmount, Ref } from "vue";

export enum RenderType {
  SVGRenderer = "svg",
  CanvasRenderer = "canvas",
}
export interface EChartsReturnType {
  getInstance: () => echarts.ECharts | null;
  setOption: (option: any) => void;
  onResize: () => void;
}

export function useECharts(
  container: Ref<HTMLDivElement | null>,
  renderer: RenderType = RenderType.CanvasRenderer
) {
  let echartsInstance: echarts.ECharts | null = null;

  function getInstance() {
    if (!echartsInstance) initEchart();
    return echartsInstance;
  }
  function initEchart() {
    if (!container) return;
    echartsInstance = echarts.init(container.value, null, { renderer });
  }

  function setOption(option) {
    if (!echartsInstance) initEchart();
    echartsInstance?.setOption(option);
  }

  function onResize() {
    echartsInstance?.resize();
  }

  function dispose() {
    echartsInstance?.dispose();
    echartsInstance = null;
  }

  onMounted(() => {
    window.addEventListener("resize", onResize);
  });
  onBeforeUnmount(() => {
    window.removeEventListener("resize", onResize);
    dispose();
  });

  return { getInstance, setOption, onResize, dispose };
}
